package com.snail.service.impl;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.snail.model.pojo.SysRole;
import com.snail.service.SysRoleService;
import com.snail.service.SysUserRoleService;
import com.snail.utils.PermissionHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 蔡徐坤
 * @Date 2025/7/17 13:33
 * @Description: 权限加载接口实现类
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private PermissionHelperUtils permissionHelperUtils;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleService sysRoleService;


    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        Long userId = Long.parseLong(loginId.toString());

        // 可以选择从 Session 拿权限（推荐做法）：
        List<String> permissions = (List<String>) StpUtil.getSession().get("permissionCodes");
        if (permissions != null) {
            return permissions;
        }
        // 兜底从数据库加载
        return permissionHelperUtils.getUserPermissionCodes(userId);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        Long userId = Long.valueOf(loginId.toString());

        // 根据用户ID获取角色对象列表（包含 code）
        List<Long> roleIds = sysUserRoleService.getRoleIdsByUserId(userId);

        if (roleIds == null || roleIds.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 再通过角色ID查询出对应的角色实体（SysRole）
        List<SysRole> roles = sysRoleService.listByIds(roleIds);

        // 3. 提取出角色编码 code
        return roles.stream()
                .map(SysRole::getCode)
                .collect(Collectors.toList());
    }
}
